import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/no_more/no_more.dart';
import 'package:pornhub_app/components/short_widget/video_base_cell.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/utils/events.dart';

import '../../../model/video_base_model.dart';

class ArroundVideoPage extends StatefulWidget {
  final int userId;
  final VideoLayout videoLayout;
  const ArroundVideoPage(
      {super.key, required this.userId, required this.videoLayout});

  @override
  State<ArroundVideoPage> createState() => _ArroundVideoPageState();
}

class _ArroundVideoPageState extends State<ArroundVideoPage> {
  final _pageSize = 20;
  final PagingController<int, VideoBaseModel> _pagingController =
      PagingController(firstPageKey: 1);
  StreamSubscription? subscription;
  StreamSubscription? layoutEvent;
  late VideoLayout layout;
  @override
  void initState() {
    layout = widget.videoLayout;
    _pagingController.addPageRequestListener((pageKey) {
      _initListData(pageKey);
    });
    subscription = eventBus.on<BloggerRefreshEvent>().listen((event) {
      if (event.tabName == "视频") {
        _pagingController.refresh();
      }
    });
    layoutEvent = eventBus.on<VideoLayoutEvent>().listen((event) {
      layout = event.layout;
      if (mounted) setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return PagedGridView(
      physics: const ClampingScrollPhysics(),
      showNewPageProgressIndicatorAsGridChild: false,
      showNewPageErrorIndicatorAsGridChild: false,
      showNoMoreItemsIndicatorAsGridChild: false,
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 8.w),
      pagingController: _pagingController,
      builderDelegate: PagedChildBuilderDelegate<VideoBaseModel>(
          noMoreItemsIndicatorBuilder: (_) {
        return const NoMore();
      }, noItemsFoundIndicatorBuilder: (_) {
        return const NoData();
      }, itemBuilder: (context, value, index) {
        return layout == VideoLayout.small
            ? VideoBaseCell.small(video: value)
            : VideoBaseCell.big(video: value);
      }),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 8.w,
          crossAxisSpacing: 12.w,
          crossAxisCount: layout == VideoLayout.small ? 2 : 1,
          childAspectRatio:
              layout == VideoLayout.small ? 182 / 146 : 374 / 240),
    );
  }

  Future _initListData(int pageKey) async {
    final videos = await httpInstance.get<VideoBaseModel>(
        url: 'video/queryPersonVideoByType',
        queryMap: {
          'videoMark': 1,
          'userId': widget.userId,
          'page': pageKey,
          'pageSize': _pageSize,
        },
        complete: VideoBaseModel.fromJson);
    final isLastPage = videos.length < _pageSize;
    if (isLastPage) {
      _pagingController.appendLastPage(videos);
    } else {
      final nextPageKey = pageKey + 1;
      _pagingController.appendPage(videos, nextPageKey as int?);
    }
  }

  @override
  void dispose() {
    subscription?.cancel();
    layoutEvent?.cancel();
    super.dispose();
  }
}
